var geoc = new BMap.Geocoder(); 
var coordinate = '';
var map = new BMap.Map("allmap"); // 创建Map实例
map.centerAndZoom(new BMap.Point(116.404, 39.915), 12); // 初始化地图,设置中心点坐标和地图级别
//	map.addControl(new BMap.MapTypeControl());   //添加地图类型控件
map.setCurrentCity("北京"); // 设置地图显示的城市 此项是必须设置的

map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
staues = true;
if(coordinate == '') {

	var geolocation = new BMap.Geolocation();
	geolocation.getCurrentPosition(function(r) {
		if(this.getStatus() == BMAP_STATUS_SUCCESS) {

			//var mk = new BMap.Marker(r.point);
			//map.addOverlay(mk);
			map.panTo(r.point);

		}
	}, {enableHighAccuracy: true});
}



var index = 0;
//以下定义了两个临时存放覆盖物对象的数组，便于后台删除和修改用。
var arraytemp = [];
var arraytemp1 = [];
map.addEventListener("click", function(e) {
	//监听点击事件 用于打点
	var coordinates = JSON.stringify(e.point);
//	document.getElementById('coordinate').value = coordinates + 'index' + index;
//	var distance = document.getElementById('distance').value;
	var distance = 1.5;
	if(isNaN(distance)) {
		document.getElementById('distance').value = 1.5;
		distance = 1500;
	} else {
		distance = distance * 1000;
	}
	draw_circle(coordinates, distance);
	
	//页面添加签到点
	var signAddr = ""
	var signHtml = "";
	var signPointDom = $("#signPoint");
	var signPoint = JSON.stringify(e.point);
	geoc.getLocation(e.point, function(rs){
		var addComp = rs.addressComponents;
		signAddr = addComp.province + addComp.city +  addComp.district +  addComp.street +  addComp.streetNumber;
		signHtml += '<div class="signPointItem col-xs-12" data-label="签到点'+index+'">\
								<p class="pointIndex" style="margin-top:3px;font-weight:bold;">签到点'+index+'：</p>\
								<div class="row cl" style="margin-top:10px;">\
									<div class="form-label col-xs-4">签到地址：</div>\
									<div class="col-xs-8"><input type="text" class="input-text" readonly="" name="title[]" value="'+signAddr+'" datatype="*"></div>\
								</div>\
								<div class="row cl" style="margin-top:10px;">\
									<div class="form-label col-xs-4">允许误差：</div>\
									<div class="col-xs-4"><input type="text" class="input-text" placeholder="允许误差" maxlength="5" onblur="baidu_removing(this)" name="deviation[]" value="1.5"></div>\
									<div class="form-label col-xs-2" style="text-align: left;">公里</div>\
									<div class="text-r col-xs-2"><input class="deleteBtn btn btn-danger radius" type="button" onclick="deletePointBtn(this)" value="删除" /></div>\
									<input class="signCoor" name="coordinate[]" type="hidden" value='+signPoint+' />\
									<input class="signDisOld" type="hidden" value="1.5" />\
								</div>\
							</div>'
		signPointDom.append(signHtml);
	});
	index = index + 1;
});

function draw_circle(point, distance, labelText) { //根据坐标和距离 画点和圆
	var newPoint = point;
	point = JSON.parse(point);
	var mk = new BMap.Marker(point);
	mk.setZIndex(index);
	mk.disableDragging();
	
	map.addOverlay(mk);
	if(labelText){
		var label = new BMap.Label(labelText, {
			offset: new BMap.Size(20, -10)
		});
		mk.setLabel(label);
	}else{
		var label = new BMap.Label("签到点" + (index+1), {
			offset: new BMap.Size(20, -10)
		});
		mk.setLabel(label);
	}
	arraytemp[index] = mk;
	//对覆盖物进行监听右键事件
	mk.addEventListener("rightclick", function(e) {
		//点右键时删除访地标及覆盖物
		deletePoint(JSON.stringify(e.currentTarget.M));
	});
	//打覆盖范围
	//生成覆盖范围覆盖物
	var circle = new BMap.Circle(point, distance, {
		strokeColor: "blue",
		strokeWeight: 2,
		strokeOpacity: 0.5
	});
	circle.addEventListener("rightclick", function(e) {
		//点右键时删除访地标及覆盖物
		deletePoint(JSON.stringify(e.currentTarget.M));
	});
	map.addOverlay(circle);
}

function baidu_removing(obj) { //根据输入的距离画图
	var coordinates = $(obj).parent().siblings(".signCoor").val();
	var distanceOld = parseFloat($(obj).parent().siblings(".signDisOld").val());
	var distance = parseFloat($(obj).val());
	var labelText = $(obj).parents(".signPointItem ").attr("data-label");
	//删除地图上旧的点和圈
	var allOverlay = map.getOverlays();
	for (var i = 1; i < allOverlay.length; i++){
		var overlayItem = JSON.stringify(allOverlay[i].M);
		if(overlayItem == coordinates){
			map.removeOverlay(allOverlay[i]);
		}
	}
	
//	var allOverlay = map.getOverlays();
//	for (var i = 1; i < allOverlay.length; i++){
//	    if(allOverlay[i].getLabel){
//	    	if(allOverlay[i].getLabel().content == labelText){
//			    allOverlay[i].setLabel(labelText);
//			    return false;
//				}
//	    }
//	}
	
	//再加上新的点和圈
	if(coordinates == '' || distance == '') {
		return false;
	}

	if(isNaN(distance)) {
		return false;
	} else {
		distance = distance * 1000;
	}
	draw_circle(coordinates, distance, labelText);
}

/****下面是拉框放大地图****/
/*
var myDrag = new BMapLib.RectangleZoom(map, {
		followText: "拖拽鼠标进行操作"
	});
	myDrag.open(); 
	*/

// 百度地图API功能
function G(id) {
	return document.getElementById(id);
}

var ac = new BMap.Autocomplete( //建立一个自动完成的对象
	{
		"input": "suggestId",
		"location": map
	});

ac.addEventListener("onhighlight", function(e) { //鼠标放在下拉列表上的事件
	var str = "";
	var _value = e.fromitem.value;
	var value = "";
	if(e.fromitem.index > -1) {
		value = _value.province + _value.city + _value.district + _value.street + _value.business;
	}
	str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

	value = "";
	if(e.toitem.index > -1) {
		_value = e.toitem.value;
		value = _value.province + _value.city + _value.district + _value.street + _value.business;
	}
	str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
	G("searchResultPanel").innerHTML = str;
});

var myValue;
ac.addEventListener("onconfirm", function(e) { //鼠标点击下拉列表后的事件
	var _value = e.item.value;
	myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
	G("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

	setPlace();
});

function setPlace() {
//	map.clearOverlays(); //清除地图上所有覆盖物
	function myFun() {
		var pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
		map.centerAndZoom(pp, 18);
		//map.addOverlay(new BMap.Marker(pp));    //添加标注
	}
	var local = new BMap.LocalSearch(map, { //智能搜索
		onSearchComplete: myFun
	});
	local.search(myValue);
}
//右键删除特定签到点(地图)
function deletePoint(coor){
	var allOverlay = map.getOverlays();
	for (var i = 1; i < allOverlay.length; i++){
		var overlayItem = JSON.stringify(allOverlay[i].M);
		if(overlayItem == coor){
			map.removeOverlay(allOverlay[i]);
			deletePointData(coor);
		}
	}
}
//点击按钮删除特定签到点(地图)
function deletePointBtn(obj){
	var point = $(obj).parent().siblings(".signCoor").val();
	deletePoint(point);
	deletePointData(point);
}
//删除特定签到点(页面数据)
function deletePointData(coor){
	$("#signPoint .signPointItem").each(function(){
		if($(this).find(".signCoor").val() == coor){
			$(this).remove();
			updatePoint();
		}
	})
}
//更新签到点的序号
function updatePoint(){
	var indexNew = 1;
	//更新全局序号
	index = $("#signPoint .signPointItem").length;
	//更新页面数据
	$("#signPoint .signPointItem").each(function(){
		var index = $(this).index()+1;
		$(this).attr("data-label", "签到点"+index);
		$(this).find(".pointIndex").html("签到点"+index+"：");
	})
	//更新地图标注
	var allOverlay = map.getOverlays();
  for (var i = 1; i < allOverlay.length; i++){
    if(allOverlay[i].getLabel){
	    var label = new BMap.Label("签到点" + indexNew, {
				offset: new BMap.Size(20, -10)
			});
			allOverlay[i].setLabel(label);
	    indexNew ++;
		}
  }
}
